<?php
class Cart extends MY_Controller{
	var $menu = array();
	var $hours = array();
	var $shop = array();
	var $delivery_hours = array();
	function __construct()
	{
		parent::__construct();
		$this->menu = cat::find('all',array('conditions'=>array('parent_id'=>NULL)));
		$this->hours= hour::find('all',array('order'=>'hour asc'));
		$this->delivery_hours= delivery_hour::find('all',array('order'=>'hour asc'));
		$this->shop = shop::find('all',array('conditions'=>array('status','1')));
	}


	function index()
	{
		if(!$this->member){
			redirect('login/cart');
		}else{
			$s = community::find('all',array('select'=>'limit_price','order'=>'limit_price asc'));
			$d = array();
			foreach ($s as $i){
				$d[] = $i->limit_price;
			}
			$d = array_unique($d);
			$data['limits'] = $d;
		
			$data['title'] = $this->title('Panier');
			$data['menu'] = cat::find('all',array('conditions'=>array('parent_id'=>NULL)));
			$data['coms'] = community::find('all',array('conditions'=>array('status'=>'active')));
			$data['sauces'] = product::find('all',array('conditions'=>array('cat_id'=>16,'status'=>! null)));
			$data['files'] = get_dir_file_info('lunch_pdf', $top_level_only = TRUE);
			$data['shop'] = shop::find('all',array('conditions'=>array('status','1')));
			$this->load->view('header',$data);
			$this->load->view('cart/cart',$data);
			$this->load->view('footer',$data);
		}
	}

	function special()
	{
		if(!$this->member){
			redirect('login/cart');
		}else{
			if(!$this->discount_delivery){
				redirect('cart');
			}else{
				$s = community::find('all',array('select'=>'limit_price','order'=>'limit_price asc'));
			$d = array();
			foreach ($s as $i){
				$d[] = $i->limit_price;
			}
			$d = array_unique($d);
			$data['limits'] = $d;
		
			$data['title'] = $this->title('Panier');
			$data['menu'] = cat::find('all',array('conditions'=>array('parent_id'=>NULL)));
			$data['coms'] = community::find('all',array('conditions'=>array('status'=>'active')));
			$data['sauces'] = product::find('all',array('conditions'=>array('cat_id'=>16,'status'=>! null)));
			$data['files'] = get_dir_file_info('lunch_pdf', $top_level_only = TRUE);
			$data['shop'] = shop::find('all',array('conditions'=>array('status','1')));
			$this->load->view('header',$data);
			$this->load->view('cart/special',$data);
			$this->load->view('footer',$data);	
					
			}
		}

	}
	
	function insert(){
	
		if($_POST){
			if(!isset($_POST['option']) || count(array_filter($_POST['option']))==0){
				$data = array('id'=>$_POST['id'],'qty'=>$_POST['qty'],'name'=>$_POST['name'],'price'=>$_POST['price'],'product_num'=>$_POST['product_num'],'options'=>NULL);
				$this->cart->insert($data);
				redirect($_POST['url']);
			}else{

				$options = array();
				$new_options = attribute_product::find(array_filter($_POST['option']),array('select' => 'attribute_name, attribute_price'));
				if( sizeof($new_options) > 1){
					foreach ($new_options as $o){
						$options[] = array('option_name'=>$o->attribute_name,'price'=>$o->attribute_price);
					}
				}else{

					$options = array(array('option_name'=>$new_options->attribute_name,'price'=>$new_options->attribute_price));

				}

				$data = array('id'=>$_POST['id'],'qty'=>$_POST['qty'],'name'=>$_POST['name'],'price'=>$_POST['price'],'product_num'=>$_POST['product_num'],'options'=>$options);
				$this->cart->insert($data);
				redirect($_POST['url']);
					
			}
		}

	}


	
	function update($special=NULL){

		if($_POST)
		{
			
		$this->cart->update($_POST);
			if($_GET){
				redirect('cart/reservation');
			}elseif($special){
				redirect('cart/special');
			}else{
				redirect('cart');
			}
		}else{
			redirect('cart');
			
		}

	}
	
	function cart_update(){
		if($_POST){
			$this->cart->update($_POST);
			if(isset($_GET)&& $_GET['url'] != NULL){
				$url = $_GET['url'];
				redirect($url);
			}else{
				show_404();
			}
			var_dump($_POST);
		}else{
			redirect('cart');
		}
		
	}
	
	
	function empty_cart()
	{
		$this->cart->destroy();
		echo json_encode('votre panier est vide.');
	}


	function takeaway($order_type=null)
	{
		$data['shop'] = shop::find('all',array('conditions'=>array('status','1')));
		$data['files'] = get_dir_file_info('lunch_pdf', $top_level_only = TRUE);
		if($order_type==''){
			redirect('cart/takeaway/normal');
		}
		if(!$this->member){redirect('login/cart');
		}else{
			if($this->cart->total()==0){
				redirect('cart');
			}else{
				if($_POST){
					$data['title'] = $this->title('validation');
					$data['menu'] = $this->menu;
					$data['post'] = $_POST;
					$data['shop_info'] = shop::find_by_id($_POST['shop_id']);
					$this->load->view('header',$data);
					$this->load->view('cart/takeaway_valid',$data);
					$this->load->view('footer',$data);
				}else{

					$data['title'] = $this->title('Panier');
					$data['menu'] = $this->menu;
					$data['hours'] = $this->hours;
					$data['shop'] = $this->shop;
					$this->load->view('header',$data);
					$this->load->view('cart/takeaway',$data);
					$this->load->view('footer',$data);
				}
			}
		}
	}

	function delivery()
	{
		$data['shop'] = shop::find('all');
		$data['files'] = get_dir_file_info('lunch_pdf', $top_level_only = TRUE);
		if(!$this->member){
			redirect('login/cart');
		}else{


			if($this->cart->total()==0){
				redirect('cart');
			}else{

				if($_POST){
					$data['title'] = $this->title('Panier');
					$data['menu'] = $this->menu;
					$data['hours'] = $this->delivery_hours;
					$data['shop'] = $this->shop;
					$com = community::find_by_id($_POST['com']);
					$data['delivery_shop'] = $com->delivery;
					$data['delivery_address'] = adresse::find('all',array('conditions'=>array('member_id'=>$this->member->id,'postal'=>$com->code)));
					$data['post'] = $_POST;
					$this->load->view('header',$data);
					$this->load->view('cart/delivery',$data);
					$this->load->view('footer',$data);
				}else{
					redirect('cart');
				}
			}
		}
	}

	function delivery_valid()
	{
		$data['shop'] = shop::find('all',array('conditions'=>array('status','1')));
		$data['files'] = get_dir_file_info('lunch_pdf', $top_level_only = TRUE);
		if(!$this->member){
			redirect('login/cart');
		}else{
			if($_POST)
			{
				$com = community::find_by_id($_POST['com_id']);
				$house_num = $_POST['number'];
				$address = $_POST['address'];
				$ring = $_POST['ring'];
				if($_POST['company']==''){
					$company = null;
				}else{
					$company = $_POST['company'];
				}
				$tele = $_POST['tele'];
				$postal = $com->code;
				$community = $com->name;
				$valid_address = adresse::find_by_member_id($this->member->id);
				if($valid_address){
					$valid_address->postal = $postal;
					$valid_address->community = $community;
					$valid_address->ring = $ring;
					$valid_address->house_num =$house_num;
					$valid_address->address = $address;
					$valid_address->tele = $tele;
					$valid_address->company = $company;
					$valid_address->save();
				}else{
					$address_data = array('id'=>'','member_id'=>$this->member->id, 'ring'=>$ring, 'postal'=>$postal,'community'=>$community,'house_num'=>$house_num,'address'=>$address,'tele'=>$tele,'company'=>$company);
					$valid_address = adresse::create($address_data);
					$valid_address->save();
				}

				$data['title'] = $this->title('Delivery');
				$data['address'] = $valid_address;
				$data['menu'] = $this->menu;
				$data['shop_info'] = shop::find_by_id($_POST['delivery_shop']);
				$data['post'] = $_POST;
				$this->load->view('header',$data);
				if(!isset($_POST['discount_type'])){
				$this->load->view('cart/delivery_valid');
				}else{
					if($this->valid_spcical_discount($com->discount_id,$_POST['discount_type'] ==TRUE)){
						$this->load->view('cart/delivery_valid_special');
					}else{
					$this->load->view('cart/delivery_valid');
					}
				}
				$this->load->view('footer');
					
					
			}else{
				redirect('cart');
			}
		}
	}

	
	function send_takeaway()
	{
		
		if(!$this->member){
			redirect('login/cart');
		}else{
			if($_POST)
			{
				if(isset($_POST['reservation'])){
					$reservation = $_POST['reservation'];
				}else{
					$reservation = null;
				}
				$contents = $this->cart->contents();
				$message = $_POST['extra_msg'];
				$shop_id = $_POST['shop_id'];
				$takeaway_time = $_POST['takeaway_time'];
				if($_POST['discount_total'] == 'NULL'){
				$discount = NULL;	
				}else{
				$discount = $_POST['discount_total'];
				}
				$member_id = $this->member->id;
				$total = $this->cart->total();
				$counter = $this->order_counter($shop_id)+1;
				$order_num = $shop_id.'-'.date('dmY').'-'.date('His').'-'.str_pad($counter, 4, '0', STR_PAD_LEFT);
				$order_type = 'take away';
				$order_data = array('order_num'=>$order_num,'order_time'=>'NOW','member_id'=>$member_id,'total'=>$total,'order_type'=>$order_type,'takeaway_time'=>$takeaway_time,'message'=>$message,'discount'=>$discount,'shop_id'=>$shop_id,'reservation'=>$reservation);
				$new_order = order::create($order_data);
					if($new_order->save()){
					foreach ($contents as $content){
						$option = $this->cart->product_options($content['rowid']);
					if($option !=NULL){
						$option_text = array();
						foreach ($option as $o){
							if($o['price'] != NULL){
								 $option_text[] = $o['option_name'].' : '.$o['price'].' €';
							}else{
								$option_text[] = $o['option_name'];
										
							}
						}
						$option = implode(' , ',$option_text);
						}else{
							$option = NULL;
						}
						$order_details = array('id'=>'','order_num'=>$new_order->order_num,'product_num'=>$content['product_num'],'product_id'=>$content['id'],'product_name'=>$content['name'],'product_price'=>$content['price'],'additional_price'=>$content['options_price'],'qty'=>$content['qty'],'option'=>$option);
						$orderitem = orderitem::create($order_details);
					}
					
					$order_list = orderitem::get_details($new_order->order_num);
					/*Create PDF*/
					$this->create_pdf($new_order,$order_list);
					/* Code for SMS */
					$member = member::find_by_id($new_order->member_id);
					 $lists = array();
					 foreach ($order_list as $value) {
					 	 
					 	if($value->qty>1){
					 		$lists[] = $value->qty.'x'.$value->product_num;
					 	}else{
					 		$lists[] = $value->product_num;
					 	}
					 	 
					 }
        			$o = implode(',',$lists);
        			 $msg = 'Emporter, T='.$new_order->takeaway_time.', P='.(number_format($new_order->total*(1-$new_order->discount),'1','.','')).'E, '.$member->lastname.' '.$member->firstname.','.$member->tel.',';
					$msg_text = $msg.'List='.$o;
					$sms_num = $new_order->shop->sms;
        			$result_sms = $this->send_sms($sms_num,$msg_text);
					$result_fax = $this->send_fax($new_order);
				if($result_sms==TRUE || $result_fax == true )
					{
						$this->cart->destroy();
						$this->send_email($new_order,$order_list);
						redirect('cart/succeed');
					}else{
						show_404();
					}
						
				}
			}else{
				redirect('cart');
			}
		}
	}

	
	function send_delivery()
	{
		if(!$this->member){
			redirect('login/cart');
		}else{

			if($_POST)
			{	
				
				if(isset($_POST['reservation'])){
					$reservation = $_POST['reservation'];
				}else{
					$reservation = null;
				}
				if($_POST['extra']==0){
					$extra = null;
				}else{
					$extra = $_POST['extra'];
				}
				$contents = $this->cart->contents();
				$message = $_POST['extra_msg'];
				if(date('l') =='Sunday' && $_POST['shop_id']==3){
				$shop_id = 1;
				}elseif ($reservation != NULL && $_POST['shop_id']==3)
				{
					$shop_id = 1;
				}else{
					$shop_id = $_POST['shop_id'];
				}
				$delivery_time = $_POST['delivery_time'];
				if($_POST['discount_total'] == 'NULL'){
				$discount = NULL;	
				}else{
				$discount = $_POST['discount_total'];
				}
				$member_id = $this->member->id;
				$total = $this->cart->total();
				$counter = $this->order_counter($shop_id)+1;
				$order_num = $shop_id.'-'.date('dmY').'-'.date('His').'-'.str_pad($counter, 4, '0', STR_PAD_LEFT);
				$order_type = 'delivery';
				$address_id = adresse::find_by_member_id($this->member->id);
				$order_data = array('order_num'=>$order_num,'order_time'=>'NOW','member_id'=>$member_id,'total'=>$total,'order_type'=>$order_type,'delivery_time'=>$delivery_time,'address_id'=>$address_id->id,'message'=>$message,'discount'=>$discount,'shop_id'=>$shop_id,'reservation'=>$reservation,'extra'=>$extra);
				$new_order = order::create($order_data);
				if($new_order->save()){
					foreach ($contents as $content){
						$option = $this->cart->product_options($content['rowid']);
						if($option !=NULL){
						$option_text = array();
						foreach ($option as $o){
							if($o['price'] != NULL){
								 $option_text[] = $o['option_name'].' : '.$o['price'].' €';
							}else{
								$option_text[] = $o['option_name'];
										
							}
						}
						$option = implode(' , ',$option_text);
						}else{
							$option = NULL;
						}
						$order_details = array('id'=>'','order_num'=>$new_order->order_num,'product_num'=>$content['product_num'],'product_id'=>$content['id'],'product_name'=>$content['name'],'product_price'=>$content['price'],'additional_price'=>$content['options_price'],'qty'=>$content['qty'],'option'=>$option);
						$orderitem = orderitem::create($order_details);
					}
					$order_list = orderitem::get_details($new_order->order_num);
					$this->create_pdf($new_order,$order_list);
					 $address = adresse::find_by_id($new_order->address_id);
					 $lists = array();
					 foreach ($order_list as $value) {
					 	 
					 	if($value->qty>1){
					 		$lists[] = $value->qty.'x'.$value->product_num;
					 	}else{
					 		$lists[] = $value->product_num;
					 	}
					 	 
					 }
        			$o = implode(',',$lists);
        			 $msg = 'Livrer, T='.$new_order->delivery_time.', P='.(number_format($new_order->total*(1-$new_order->discount)+$new_order->extra,'1','.','')).'E, '.$address->ring.','.$address->house_num.' '.$address->address.','.$address->postal.', '.$address->tele.',';
					$msg_text = $msg.'List='.$o;
					$sms_num = $new_order->shop->sms;
        			$result_sms = $this->send_sms($sms_num,$msg_text);
        			$result_fax = $this->send_fax($new_order);
					if( $result_sms == TRUE || $result_fax == TRUE )
					{
						$this->cart->destroy();
						$this->send_email($new_order,$order_list);
							
						redirect('cart/succeed');
					}else{
						show_404();
					}
				}else{
					redirect('cart');
				}
			}
		}
	}
	
	function succeed()
	{
		if(!$this->member){
			redirect('login/cart');
		}else{
			$data['member'] = $this->member;
			$data['title'] = $this->title('succeed');
			$data['menu'] = $this->menu;
			$data['files'] = get_dir_file_info('lunch_pdf', $top_level_only = TRUE);
			$data['shop'] = shop::find('all',array('conditions'=>array('status','1')));
			$this->load->view('header',$data);
			$this->load->view('cart/succeed',$data);
			$this->load->view('footer',$data);
		}
	}

	private function create_pdf($order,$order_details)
	{
		$this->load->helper(array('dompdf', 'file'));
		// page info here, db calls, etc.
		if($order->address_id !=NULL){
			$data['address'] = adresse::find_by_id($order->address_id);
		}
		$data['member'] = $this->member;
		$data['order']= $order;
		$data['order_details'] = $order_details;
		$html = $this->load->view('pdfs/order_note', $data,TRUE);
		$bon= pdf_create($html, '',false);
		//write_file('application/order_files/order_'.str_pad($order->id, 7, '0', STR_PAD_LEFT).'.pdf', $bon);
		write_file('application/order_files/order_'.$order->order_num.'.pdf', $bon);
		//if you want to write it to disk and/or send it as an attachment
	}

	private function send_fax($order)
	{
		/**************** Settings begin **************/
		$user_data = fax_account::find('all');
		$username = $user_data[0]->username; // Enter your Interfax username here
		$password = $user_data[0]->password; // Enter your Interfax password here
		$faxnumber = $order->shop->fax; // Enter your designated fax number here in the format +[country code][area code][fax number], for example: +12125554874
		//$texttofax = 'My text goes here'; // Enter your fax contents here
		$filename = 'application/order_files/order_'.str_pad($order->id, 7, '0', STR_PAD_LEFT).'.pdf';
		$filetype = 'PDF'; // If $texttofax is regular text, enter TXT here. If $texttofax is HTML enter HTML here
			
		/**************** Settings end ****************/
		// Open File
		if( !($fp = fopen($filename, "r"))){
			// Error opening file
			echo "Error opening file";
			exit;
		}

		// Read data from the file into $data
		$data = "";
		while (!feof($fp)) $data .= fread($fp,1024);
		fclose($fp);

		$client = new SoapClient("http://ws.interfax.net/dfs.asmx?wsdl");
		$params = new stdClass();
		$params->Username  = $username;
		$params->Password  = $password;
		$params->FaxNumber = $faxnumber;
		//$params->Data      = $texttofax;
		$params->FileData  = $data;
		$params->FileType  = $filetype;

		$result = $client->Sendfax($params);
		if($result->SendfaxResult>0){
			return true;
		}else{
			return false;
		}
			
	}
	private function send_email($order,$order_details)
	{
		if($order->address_id !=NULL){
			$data['address'] = adresse::find_by_id($order->address_id);
		}
		$data['member'] = $this->member;
		$data['order']= $order;
		$data['order_details'] = $order_details;
		$config['protocol'] = 'mail';
		$config['wordwrap'] = FALSE;
		$config['mailtype'] = 'html';
		$config['charset'] = 'utf-8';
		$config['crlf'] = "\r\n";
		$config['newline'] = "\r\n";
		$this->email->initialize($config);
		$this->email->from('no-reply@neufneufdragon.be', 'no-reply@neufneufdragon.be');
		$this->email->to($order->member->email);
		$this->email->subject('Confirmation de commande neuf-neuf dragon / Bevestiging van bestelling bij neuf-neuf dragon / neuf-neuf dragon order confirmation');

		$email = $this->load->view('emails/order_note',$data,TRUE);
		$this->email->message($email);
		$this->email->send();
	}
	
	private function send_sms($sms_num,$msg_text)
	{
		 // load library
        $this->load->library('nexmo');
        // set response format: xml or json, default json
        $this->nexmo->set_format('json');
         // **********************************Text Message*************************************
       $from = '32476982676';
        $to = $sms_num;
        	
        $message = array(
            'text' => $msg_text
        );
        $response = $this->nexmo->send_message($from, $to, $message);
        
        if( $response->messages[0]->status == 0 ){
        	return TRUE;
        }else{
        	return FALSE;
        }
       
	} 
	
	private function order_counter($shop_id = NULL)
	{
		if($shop_id !=NULL){
		$today = date('Y-m-d');
		$start_today = $today." 00:00:00";
		$end_today = $today." 23:59:59"; 
		$total = order::find('all', array('select'=>'order_num','conditions'=>array('order_time >=? AND order_time <? AND shop_id=?',$start_today, $end_today,$shop_id)));
		return count($total);
		}
	}
	
	private function valid_spcical_discount($id = NULL, $discount_type = NULL)
	{
		if(!$this->discount_delivery){
			return FALSE;
		}else{
			if($discount_type==NULL){
				return FALSE;
			}elseif($id && $discount_type == 'discount_delivery'){
				if($id == $this->discount_delivery[0]->id){
					return TRUE;
				}
			}
		}
	}	
}